<!doctype html>
<html>
	<head>
		<meta charset="utf-8" />
	</head>
	<style>
		#canvas {
			display: block;
			margin: 100px auto 0;
			border: 1px solid #d3d3d3;
		}
	</style>

	<body>
		<canvas id="canvas" width="500" height="500"></canvas>
		<script>
			//绘制贪吃蛇
			var canvas = document.getElementById("canvas");
			var ctx = canvas.getContext("2d"); //绘制了一个2d绘图空间，画笔
			var r = [{
				x: 10,
				y: 9
			}, {
				x: 10,
				y: 8
			}]; //r数组代表贪吃蛇的坐标
			ctx.shadowBlur = 1;
			ctx.shadowColor = "black";
			ctx.fillStyle="yellow";
			var co = 40; //默认向下走
			var e = null;//食物的坐标
             zb=new Object();
			function onframe() {
				if(e) {
					//食物添加
					if(co == 40 && r[0].x == e.x && r[0].y + 1 == e.y ||
						co == 39 && r[0].x + 1 == e.x && r[0].y == e.y ||
						co == 38 && r[0].x == e.x && r[0].y - 1 == e.y ||
						co == 37 && r[0].x - 1 == e.x && r[0].y == e.y) {
						r.unshift(e);//向前添加元素
						e = null;
					}
				}

				//将数组中最后一个元素放到首部
				r.unshift(r.pop());
				switch(co) {
					case 37: //向左
						r[0].x = r[1].x - 1;
						r[0].y = r[1].y;
						break;
					case 38:
						r[0].x = r[1].x;
						r[0].y = r[1].y - 1;
						break;
					case 39:
						r[0].x = r[1].x + 1;
						r[0].y = r[1].y;
						break;
					case 40:
						r[0].x = r[1].x;
						r[0].y = r[1].y + 1;
						break;
				}
				ctx.clearRect(0, 0, 500, 500);
				//贪吃蛇的绘制
				for(var i = 0; i < r.length; i++) {
					ctx.fillRect(r[i].x * 10, r[i].y * 10, 10, 10);
				}
				zb.x=r[0].x;
				zb.y=r[0].y;
				//绘制食物
				if(e == null) {
					//给坐标值
					e = {
						x: (Math.random() * 50 >>> 0),
						y: (Math.random() * 50 >>> 0)
					};
				}

				if(e) {
					ctx.fillRect(e.x * 10, e.y * 10, 10, 10);
				}
			}

			//加入键盘事件用键盘来控制蛇的前进方向
			document.onkeyup = function(event) {
				if(event.keyCode >= 37 && event.keyCode <= 40 && Math.abs(event.keyCode - co) != 2) {
					co = event.keyCode;
				}
			}
		setInterval(onframe, 100);
		</script>
	</body>

</html>